﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using BYFW.DAL;
using System.Data;
using System.Collections;
using EPocalipse.IFilter;

namespace BYFW.SFL
{
    public class PDFOP
    {
        public static string ParseText(string fileName)
        {
            //PDDocument doc = PDDocument.load(fileName);
            //PDFTextStripper stripper = new PDFTextStripper();
            //return stripper.getText(doc);
            //Aspose.Pdf.Kit.PdfExtractor p = new Aspose.Pdf.Kit.PdfExtractor();
            //p.BindPdf(fileName);
            //p.ExtractTextMode = 0;
            //p.ExtractText();
            //p.GetText(@"C:\FTP\ttt.txt");
            //return "";

            TextReader reader = new FilterReader(fileName);
            using (reader)
            {
                string res = reader.ReadToEnd();
                return res;
            }
        }

        private void Test()
        {
            string fileName = @"c:\ftp\4.pdf";
            DateTime start = DateTime.Now;
            string t = ParseText(fileName);
           // Console.WriteLine(t);
            DateTime end = DateTime.Now;
            Console.WriteLine((end - start).Milliseconds);
            Console.WriteLine(t);
        }
    }

    public class TestSQLFT
    {
        private TestSQLFT()
        {
            dbName = "testFT_01";
            tn = "FT";
            connStr = string.Format("server=localhost;uid=sa;password=password123$;database={0}", dbName);
            db = DBFactory.GetDBOP(connStr, EDBType.SimpleSQL);
        }
        string dbName = "";
        string connStr = "";
        string tn = "";
        IDBOP db = null;

        private void TEST_NormalFTInitial()
        {
            //this.DB_CreateTable(tn);
            this.DB_ClearData(tn);
            //this.DB_InsertTestData1(tn, 10);
            this.DB_InsertTestData2(tn);
        }

        private void DB_CreateTable(string tn)
        {
            string sql_dropTable = string.Format("drop table {0}", tn);
            string sql = string.Format(@"
CREATE TABLE [dbo].[{0}](
	[id] [int] IDENTITY(1,1) NOT NULL,
	[name] [nvarchar](50) NULL,
	[comment] [nvarchar](max) NULL,
 CONSTRAINT [PK_{0}] PRIMARY KEY CLUSTERED 
(
	[id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
", tn);
            TryAction(delegate() { db.ExecuteNonQuery(sql_dropTable); });
            TryAction(delegate() { db.ExecuteNonQuery(sql); });
        }
        private void DB_InsertTestData1(string tn, int cnt)
        {
            string comment = File.ReadAllText(@"c:\ftp\test.txt");
            //Console.WriteLine(comment);
            string name = Guid.NewGuid().ToString().Substring(0, 8);
            Hashtable ht = new Hashtable();
            ht.Add("name", name);
            ht.Add("comment", comment);
            for (int i = 0; i < cnt; i++)
            {
                db.InsertBlob(tn, ht);
                Console.WriteLine(i + 1);
            }
            string sql = string.Format("select count(*) from {0}", tn);
            DataTable dt = db.Select(sql).Tables[0];
            Console.WriteLine(db.ExecuteScalar(sql));
        }
        private void DB_InsertTestData2(string tn)
        {
            string txt = @"团购机票
北京至曼谷往返机票
特价机票提前45天购票可享受4折
9月份特价机票：国内机票2-6折
北京出港近期国内特价机票
北京联合机票网6月份非洲特价
嘉旅航空特价机票053
桂林出港12月打折机票";
            string[] txts = txt.Split("\r\n".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
            string sql = "insert into {0} (comment) values('{1}')";
            for (int i = 0; i < txts.Length; i++)
            {
                db.ExecuteNonQuery(string.Format(sql, tn, txts[i]));
            }
        }
        private void DB_ClearData(string tn)
        {
            string sql = "truncate table {0}";
            db.ExecuteNonQuery(string.Format(sql, tn));
        }


        private void DB_TEST()
        {
            string tn = "DOC";
            //tn = "DOC_2";
            string cat = "PDF_Cat";
            //this.DB_CreateFT(cat);
            this.DB_CreateTableFT(tn, cat);
            //this.DB_CreateTable(tn);
            //this.DB_InsertTestData(tn, 100);
            this.DB_SelectSpeed(tn);
        }

        
        private void DB_SelectSpeed(string tn)
        {
            string sql = string.Format("select count(*) from {0} where comment like '%票%'", tn);
            DateTime dtStart = DateTime.Now;
            DataTable dt = db.Select(sql).Tables[0];
            DateTime dtEnd = DateTime.Now;
            Console.WriteLine((dtEnd - dtStart).Milliseconds * 1.0 / 1000 + " s");
            Console.WriteLine(dt.Rows.Count);
        }
        private void DB_CreateFT(string cat)
        {
            string sql = string.Format(@"
EXEC sp_fulltext_database 'enable'
EXEC sp_fulltext_catalog '{0}', 'create', 'c:\ftp\ft'
", cat);
            db.ExecuteNonQuery(sql);
        }
        private void DB_CreateTableFT(string tn, string cat)
        {
            string sql = string.Format(@"
--EXEC sp_fulltext_table '{0}', 'create', '{1}','PK_{0}'
--EXEC sp_fulltext_column '{0}','comment','add'
EXEC sp_fulltext_table '{0}','activate'
EXEC sp_fulltext_table '{0}', 'start_incremental'
EXEC sp_fulltext_table {0}, 'Start_change_tracking'
EXEC sp_fulltext_table {0}, 'Start_background_updateindex'
", tn, cat);
            db.ExecuteNonQuery(sql);
        }


        private void TryAction(Action act)
        {
            try
            {
                act();
            }
            catch { }
        }

        private void DB_TempSelect()
        {
            string word = "免费";
            string field = "info2";
            string sql = string.Format(@"select count(*) from myinfo where {0} like '%{1}%'", field, word);
            sql = string.Format(@"select count(*) from myinfo where freetext({0}, '{1}')", field, word);
            DateTime dtStart = DateTime.Now;
            DataTable dt = db.Select(sql).Tables[0];
            DateTime dtEnd = DateTime.Now;
            Console.WriteLine((dtEnd - dtStart).Milliseconds * 1.0 / 1000 + " s");
            Console.WriteLine(dt.Rows.Count);
        }

        private void Test_SQL()
        {
            string f = @"[id]
      ,[name]
      ,[comment]
      ,[enterpriseID]
      ,[releaseDT]
      ,[implementDT]
      ,[isValid]
      ,[categoryID]
      ,[organization]
      ,[referenceNumber]
      ,[fileName]
      ,[fileExtension]
      ,[catalogID]
      ,[docType]
      ,[uploadDT]
      ,[summary]
      ,[keyItems]
      ,[invalidDescription]
      ,[comment1]
      ,[comment2]
      ,[comment3]
      ,[comment4]
      ,[comment5]
      ,[invalidList]
      ,[isConverted]";
            string[] fns = f.Split("\r\n".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
            StringBuilder sb = new StringBuilder(100);
            for (int i = 0; i < fns.Length; i++)
            {
                sb.Append("t_codification." + fns[i].Trim().TrimStart(',') + ",");
            }
            Console.WriteLine(sb.ToString());
                    
        }
    }
    /*
    public class TestLucene
    {
        public TestLucene()
        {
        }
        /*
         * 除了FSDirectory，还可以使用RAMDirectory。
注意：FSDirectory.GetDirectory 的create参数，为true时将删除已有索引库文件，可以通过IndexReader.IndexExists() 方法判断。
将索引库载入内存，以提高搜索速度。
private Directory directory = new RAMDirectory(FSDirectory.GetDirectory("c:\\", false));
或
private Directory directory = new RAMDirectory("c:\\");
         * 

        private const string FieldName = "name";
        private const string FieldValue = "value";
        private Lucene.Net.Store.Directory directory = null;
        private Analyzer analyzer = new StandardAnalyzer();
        private void Index()
        {
            IndexWriter writer = new IndexWriter(directory, analyzer, true);
            writer.SetMaxFieldLength(1000);
            for (int i = 1; i <= 100; i++)
            {
                Document document = new Document();
                document.Add(new Field(FieldName, "name" + i, Field.Store.YES, Field.Index.UN_TOKENIZED));
                document.Add(new Field(FieldValue, File.ReadAllText(@"c:\ftp\test.txt"), Field.Store.YES, Field.Index.TOKENIZED));
                writer.AddDocument(document);
            }
            writer.Optimize();
            writer.Close();
        }

        private void Search()
        {
            Query query = new QueryParser(FieldName, analyzer).Parse("*a*");
            IndexSearcher searcher = new IndexSearcher(directory);
            Hits hits = searcher.Search(query);
            Console.WriteLine("符合条件记录:{0}; 索引库记录总数:{1}", hits.Length(), searcher.MaxDoc());
            for (int i = 0; i < hits.Length(); i++)
            {
                int docId = hits.Id(i); string name = hits.Doc(i).Get(FieldName);
                string value = hits.Doc(i).Get(FieldValue);
                float score = hits.Score(i);
                Console.WriteLine("{0}: DocId:{1}; Name:{2}; Value:{3}; Score:{4}", i + 1, docId, name, value, score);
            }
            searcher.Close();
        }

        private void T()
        {
            this.Index();
            this.Search();
        }

        static string connStr = "server=localhost;uid=sa;password=password123$;database=test";
        IDBOP db = DBFactory.GetDBOP(connStr, EDBType.SimpleSQL);

        private void DB_TEST()
        {
            string tn = "DOC";
            //tn = "DOC_2";
            string cat = "PDF_Cat";
            //this.DB_CreateFT(cat);
            this.DB_CreateTableFT(tn, cat);
            //this.DB_CreateTable(tn);
            //this.DB_InsertTestData(tn, 100);
            this.DB_SelectSpeed(tn);
        }

        private void DB_InsertTestData(string tn, int cnt)
        {
            string comment = File.ReadAllText(@"c:\ftp\test.txt");
            string name = Guid.NewGuid().ToString().Substring(0, 8);
            Hashtable ht = new Hashtable();
            ht.Add("name", name);
            ht.Add("comment", comment);
            for (int i = 0; i < cnt; i++)
            {
                db.InsertBlob(tn, ht);
                Console.WriteLine(i + 1);
            }
            string sql = string.Format("select * from {0}", tn);
            DataTable dt = db.Select(sql).Tables[0];
            Console.WriteLine(dt.Rows.Count);
        }
        private void DB_SelectSpeed(string tn)
        {
            string sql = string.Format("select count(*) from {0} where comment like '%票%'", tn);
            DateTime dtStart = DateTime.Now;
            DataTable dt = db.Select(sql).Tables[0];
            DateTime dtEnd = DateTime.Now;
            Console.WriteLine((dtEnd - dtStart).Milliseconds * 1.0 / 1000 + " s");
            Console.WriteLine(dt.Rows.Count);
        }
        private void DB_CreateTable(string tn)
        {
            string sql_dropTable = string.Format("drop table {0}", tn);
            string sql = string.Format(@"
CREATE TABLE [dbo].[{0}](
	[id] [int] IDENTITY(1,1) NOT NULL,
	[name] [nvarchar](50) NULL,
	[comment] [nvarchar](max) NULL,
 CONSTRAINT [PK_{0}] PRIMARY KEY CLUSTERED 
(
	[id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
", tn);
            TryAction(delegate() { db.ExecuteNonQuery(sql_dropTable); });
            TryAction(delegate() { db.ExecuteNonQuery(sql); });
        }
        private void DB_CreateFT(string cat)
        {
            string sql = string.Format(@"
EXEC sp_fulltext_database 'enable'
EXEC sp_fulltext_catalog '{0}', 'create', 'c:\ftp\ft'
", cat);
            db.ExecuteNonQuery(sql);
        }
        private void DB_CreateTableFT(string tn, string cat)
        {
            string sql = string.Format(@"
--EXEC sp_fulltext_table '{0}', 'create', '{1}','PK_{0}'
--EXEC sp_fulltext_column '{0}','comment','add'
EXEC sp_fulltext_table '{0}','activate'
EXEC sp_fulltext_table '{0}', 'start_incremental'
EXEC sp_fulltext_table {0}, 'Start_change_tracking'
EXEC sp_fulltext_table {0}, 'Start_background_updateindex'
", tn, cat);
            db.ExecuteNonQuery(sql);
        }

        private void DB_()
        {
            string txt = @"团购机票
北京至曼谷往返机票
特价机票提前45天购票可享受4折
9月份特价机票：国内机票2-6折
北京出港近期国内特价机票
北京联合机票网6月份非洲特价
嘉旅航空特价机票053
桂林出港12月打折机票";
            string[] txts = txt.Split("\r\n".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
            string sql = "insert into ft_1 (name) values('{0}')";
            for (int i = 0; i < txts.Length; i++)
            {
                db.ExecuteNonQuery(string.Format(sql, txts[i]));
            }
        }

        private void TryAction(Action act)
        {
            try
            {
                act();
            }
            catch { }
        }

        private void DB_TempSelect()
        {
            string word = "免费";
            string field = "info2";
            string sql = string.Format(@"select count(*) from myinfo where {0} like '%{1}%'", field, word);
            sql = string.Format(@"select count(*) from myinfo where freetext({0}, '{1}')", field, word);
            DateTime dtStart = DateTime.Now;
            DataTable dt = db.Select(sql).Tables[0];
            DateTime dtEnd = DateTime.Now;
            Console.WriteLine((dtEnd - dtStart).Milliseconds * 1.0 / 1000 + " s");
            Console.WriteLine(dt.Rows.Count);
        }
    }
    */
    public class LuceneFullText
    {
    }
}


